package com.agent.controller;

import com.baidubce.appbuilder.base.exception.AppBuilderServerException;
import com.baidubce.appbuilder.console.appbuilderclient.AppBuilderClient;
import com.baidubce.appbuilder.model.appbuilderclient.AppBuilderClientIterator;
import com.baidubce.appbuilder.model.appbuilderclient.AppBuilderClientResult;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

/**
 * @Author worlt
 * @Date 2025/1/29 下午4:01
 */

@RestController
@RequestMapping("/appbuilder")
public class AppBuilderController {
    private static final Logger logger = LoggerFactory.getLogger(SmartAgentController.class);

    @Value("${appbuilder.token}")
    private String appBuilderToken;

    @Value("${appbuilder.app-id}")
    private String appId;

    @PostMapping("/conversation")
    public ResponseEntity<Map<String, Object>> sendMessage(@RequestBody String message) {
        Map<String, Object> response = new HashMap<>();
        try {
            // 设置环境变量
            System.setProperty("APPBUILDER_TOKEN", appBuilderToken);

            // 创建 AppBuilderClient 实例
            AppBuilderClient builder = new AppBuilderClient(appId);

            // 创建会话
            String conversationId = builder.createConversation();
            logger.info("Conversation ID: {}", conversationId);

            // 发送消息并获取响应
            AppBuilderClientIterator iterator = builder.run(message, conversationId, new String[]{}, false);
            StringBuilder answer = new StringBuilder();
            while (iterator.hasNext()) {
                answer.append(iterator.next().getAnswer());
            }

            // 构造响应
            response.put("message", "成功");
            response.put("conversationId", conversationId);
            response.put("answer", answer.toString());
            System.out.println(answer);
            return ResponseEntity.ok(response);
        } catch (Exception e) {
            logger.error("Error occurred: {}", e.getMessage(), e);
            response.put("message", "失败");
            response.put("error", e.getMessage());
            return ResponseEntity.status(500).body(response);
        }
    }
}
